/**
 * HTTP请求工具
 * 基于axios封装，提供统一的请求和响应处理
 * 集成缓存、重试机制和性能优化
 */

import axios, {
  AxiosInstance,
  InternalAxiosRequestConfig,
  AxiosResponse,
  AxiosRequestConfig,
} from "axios";
import { message } from "antd";
import ENV_CONFIG from "../config/env";
import { AuthService } from "./auth";

// 扩展axios配置类型
interface ExtendedAxiosRequestConfig extends InternalAxiosRequestConfig {
  metadata?: { startTime: number };
  retryCount?: number;
}

// 统一的token获取函数
const getAuthToken = (): string | null => {
  return AuthService.getToken();
};

// 统一的token清理函数
const clearAllTokens = () => {
  AuthService.removeToken();
  AuthService.clearAllCookies();
};

// 请求缓存Map
const requestCache = new Map<string, { data: any; timestamp: number }>();
const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

// 生成缓存key
const generateCacheKey = (config: AxiosRequestConfig): string => {
  const { url, method, params, data } = config;
  return `${method}_${url}_${JSON.stringify(params)}_${JSON.stringify(data)}`;
};

// 检查缓存是否有效
const isCacheValid = (timestamp: number): boolean => {
  return Date.now() - timestamp < CACHE_DURATION;
};

// 创建axios实例
const httpClient: AxiosInstance = axios.create({
  baseURL: ENV_CONFIG.API_BASE_URL,
  timeout: 30000, // 增加超时时间到30秒
  withCredentials: false, // 由于使用代理，暂时关闭
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
    Accept: "application/json",
    "Cache-Control": "no-cache",
    Pragma: "no-cache",
  },
});

// 请求拦截器
httpClient.interceptors.request.use(
  (config: ExtendedAxiosRequestConfig) => {
    // 开发环境打印请求信息
    if (ENV_CONFIG.DEBUG) {
      console.log("🚀 HTTP Request:", {
        url: config.url,
        method: config.method?.toUpperCase(),
        baseURL: config.baseURL,
        fullURL: `${config.baseURL || ""}${config.url}`,
        data: config.data,
        params: config.params,
        headers: config.headers,
      });
    }

    // 使用AuthService统一获取token
    const token = getAuthToken();
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
      if (ENV_CONFIG.DEBUG) {
        console.log("🔑 添加认证头:", `Bearer ${token.substring(0, 20)}...`);
        console.log("🔍 完整请求URL:", `${config.baseURL || ""}${config.url}`);
        console.log("🔍 请求方法:", config.method?.toUpperCase());
      }
    } else {
      if (ENV_CONFIG.DEBUG) {
        console.warn("⚠️ 未找到Token或headers未定义:", {
          hasToken: !!token,
          hasHeaders: !!config.headers,
        });
        // 显示AuthService的详细状态
        console.log("🔍 AuthService状态:", {
          hasToken: !!AuthService.getToken(),
          isAuthenticated: AuthService.isAuthenticated(),
          localStorage: !!localStorage.getItem("authToken"),
          sessionStorage: !!sessionStorage.getItem("authToken"),
        });
      }
    }

    // 添加请求时间戳
    config.metadata = { startTime: Date.now() };

    return config;
  },
  (error) => {
    console.error("❌ Request Error:", error);
    return Promise.reject(error);
  }
);

// 响应拦截器
httpClient.interceptors.response.use(
  (response: AxiosResponse) => {
    // 开发环境打印响应信息和耗时
    if (ENV_CONFIG.DEBUG) {
      const config = response.config as ExtendedAxiosRequestConfig;
      const duration = Date.now() - (config.metadata?.startTime || 0);
      console.log("✅ HTTP Response:", {
        url: response.config.url,
        status: response.status,
        statusText: response.statusText,
        duration: `${duration}ms`,
        data: response.data,
        headers: response.headers,
      });
    }

    // 检查响应数据格式
    if (response.data && typeof response.data === "object") {
      // 如果后端返回了错误码
      if (
        response.data.code &&
        response.data.code !== 200 &&
        response.data.code !== "200"
      ) {
        console.warn("⚠️ 业务错误:", response.data);
        // 不在这里抛出错误，让调用方处理
      }
    }

    return response;
  },
  async (error) => {
    console.error("❌ Response Error:", {
      message: error.message,
      code: error.code,
      response: error.response,
      request: error.request,
      config: error.config,
    });

    // 重试机制
    const config = error.config as ExtendedAxiosRequestConfig;
    if (!config.retryCount) {
      config.retryCount = 0;
    }

    const shouldRetry =
      (config.retryCount < 3 && // 最多重试3次
        error.code === "ECONNREFUSED") || // 连接被拒绝
      error.code === "NETWORK_ERROR" || // 网络错误
      (error.response?.status >= 500 &&
        error.response?.status < 600 && // 服务器错误
        config.method?.toLowerCase() === "get"); // 只对GET请求重试

    if (shouldRetry) {
      config.retryCount = (config.retryCount || 0) + 1;
      console.log(`🔄 重试请求 (${config.retryCount}/3):`, config.url);
      return new Promise((resolve) => {
        setTimeout(
          () => resolve(httpClient(config)),
          1000 * (config.retryCount || 1) // 递增延时，添加默认值防止undefined
        );
      });
    }

    // 401错误：认证失败处理
    if (error.response?.status === 401) {
      console.warn("🚫 认证失败，清除认证信息");

      // 尝试刷新token
      try {
        const newToken = await AuthService.refreshToken();
        if (newToken && config) {
          // 重试原请求
          config.headers.Authorization = `Bearer ${newToken}`;
          return httpClient.request(config);
        }
      } catch (refreshError) {
        console.error("Token刷新失败:", refreshError);
      }

      // 刷新失败，清除认证信息并跳转登录
      clearAllTokens();

      // 避免在登录页面重复跳转
      if (!window.location.pathname.includes("/login")) {
        window.location.href = "/login";
      }
    }

    // 403错误：权限不足
    if (error.response?.status === 403) {
      message.error("权限不足，请联系管理员");
    }

    // 404错误：资源不存在
    if (error.response?.status === 404) {
      console.warn("⚠️ 资源不存在:", error.config.url);
    }

    // 500错误：服务器内部错误
    if (error.response?.status >= 500) {
      message.error("服务器错误，请稍后重试");
    }

    return Promise.reject(error);
  }
);

// 获取缓存响应
const getCachedResponse = <T>(cacheKey: string): T | null => {
  const cached = requestCache.get(cacheKey);
  if (cached && isCacheValid(cached.timestamp)) {
    return cached.data;
  }
  return null;
};

// 设置缓存响应
const setCachedResponse = (cacheKey: string, data: any): void => {
  requestCache.set(cacheKey, {
    data,
    timestamp: Date.now(),
  });
};

// GET请求
export const httpGet = async <T = any>(
  url: string,
  params?: any,
  config?: AxiosRequestConfig & { useCache?: boolean }
): Promise<T> => {
  const requestConfig = { ...config, params };
  const cacheKey = generateCacheKey({ url, method: "GET", params });

  // 检查缓存
  if (config?.useCache !== false) {
    const cachedResponse = getCachedResponse<T>(cacheKey);
    if (cachedResponse) {
      console.log("📦 使用缓存响应:", url);
      return cachedResponse;
    }
  }

  try {
    const response = await httpClient.get<T>(url, requestConfig);

    // 缓存成功响应
    if (config?.useCache !== false && response.data) {
      setCachedResponse(cacheKey, response.data);
    }

    return response.data;
  } catch (error) {
    throw error;
  }
};

// POST请求
export const httpPost = async <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  try {
    const response = await httpClient.post<T>(url, data, config);
    return response.data;
  } catch (error) {
    throw error;
  }
};

// PUT请求
export const httpPut = async <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  try {
    const response = await httpClient.put<T>(url, data, config);
    return response.data;
  } catch (error) {
    throw error;
  }
};

// DELETE请求
export const httpDelete = async <T = any>(
  url: string,
  config?: AxiosRequestConfig
): Promise<T> => {
  try {
    const response = await httpClient.delete<T>(url, config);
    return response.data;
  } catch (error) {
    throw error;
  }
};

// 文件上传
export const httpUpload = async <T = any>(
  url: string,
  file: File,
  onProgress?: (progress: number) => void,
  config?: AxiosRequestConfig
): Promise<T> => {
  const formData = new FormData();
  formData.append("file", file);

  try {
    const response = await httpClient.post<T>(url, formData, {
      ...config,
      headers: {
        ...config?.headers,
        "Content-Type": "multipart/form-data",
      },
      onUploadProgress: (progressEvent) => {
        if (onProgress && progressEvent.total) {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          onProgress(percentCompleted);
        }
      },
    });
    return response.data;
  } catch (error) {
    throw error;
  }
};

// 清除相关缓存
const clearRelatedCache = (url: string): void => {
  const keysToDelete: string[] = [];
  requestCache.forEach((_, key) => {
    if (key.includes(url)) {
      keysToDelete.push(key);
    }
  });
  keysToDelete.forEach((key) => requestCache.delete(key));
};

// 清除所有缓存
export const clearAllCache = (): void => {
  requestCache.clear();
};

// 批量请求
export const batchRequest = async <T = any>(
  requests: Array<() => Promise<T>>,
  concurrency: number = 3
): Promise<T[]> => {
  const results: T[] = [];

  for (let i = 0; i < requests.length; i += concurrency) {
    const batch = requests.slice(i, i + concurrency);
    const batchResults = await Promise.allSettled(
      batch.map((request) => request())
    );

    batchResults.forEach((result, index) => {
      if (result.status === "fulfilled") {
        results[i + index] = result.value;
      } else {
        console.error(`批量请求失败 [${i + index}]:`, result.reason);
        throw result.reason;
      }
    });
  }

  return results;
};

// 请求跟踪（防重复请求）
interface RequestState {
  pending: Set<string>;
  completed: Map<string, { success: boolean; timestamp: number }>;
}

const requestState: RequestState = {
  pending: new Set(),
  completed: new Map(),
};

// 生成请求ID
const generateRequestId = (url: string, method: string = "GET"): string => {
  return `${method.toUpperCase()}_${url}`;
};

// 检查是否重复请求
const isDuplicateRequest = (url: string, method: string = "GET"): boolean => {
  const requestId = generateRequestId(url, method);
  return requestState.pending.has(requestId);
};

// 添加请求跟踪
const addRequestTracking = (url: string, method: string = "GET"): string => {
  const requestId = generateRequestId(url, method);
  requestState.pending.add(requestId);
  return requestId;
};

// 完成请求跟踪
const completeRequestTracking = (requestId: string, success: boolean): void => {
  requestState.pending.delete(requestId);
  requestState.completed.set(requestId, {
    success,
    timestamp: Date.now(),
  });

  // 清理旧的完成记录（保留最近1小时）
  const oneHourAgo = Date.now() - 60 * 60 * 1000;
  Array.from(requestState.completed.entries()).forEach(([id, info]) => {
    if (info.timestamp < oneHourAgo) {
      requestState.completed.delete(id);
    }
  });
};

// 带防重复的GET请求
export const httpGetWithTracking = async <T = any>(
  url: string,
  params?: any,
  config?: AxiosRequestConfig & { useCache?: boolean; allowDuplicate?: boolean }
): Promise<T> => {
  if (!config?.allowDuplicate && isDuplicateRequest(url, "GET")) {
    throw new Error("重复请求被阻止");
  }

  const requestId = addRequestTracking(url, "GET");

  try {
    const result = await httpGet<T>(url, params, config);
    completeRequestTracking(requestId, true);
    return result;
  } catch (error) {
    completeRequestTracking(requestId, false);
    throw error;
  }
};

// 带防重复的POST请求
export const httpPostWithTracking = async <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig & { allowDuplicate?: boolean }
): Promise<T> => {
  if (!config?.allowDuplicate && isDuplicateRequest(url, "POST")) {
    throw new Error("重复请求被阻止");
  }

  const requestId = addRequestTracking(url, "POST");

  try {
    const result = await httpPost<T>(url, data, config);
    completeRequestTracking(requestId, true);
    return result;
  } catch (error) {
    completeRequestTracking(requestId, false);
    throw error;
  }
};

// 刷新认证token
export const refreshAuthToken = async (): Promise<string> => {
  try {
    const newToken = await AuthService.refreshToken();
    if (!newToken) {
      throw new Error("Token刷新失败");
    }
    return newToken;
  } catch (error) {
    console.error("刷新token失败:", error);
    clearAllTokens();
    throw error;
  }
};

// 健康检查
export const healthCheck = async (): Promise<boolean> => {
  try {
    await httpGet("/health", undefined, { useCache: false });
    return true;
  } catch (error) {
    return false;
  }
};

// 获取请求统计
export const getRequestStats = () => {
  return {
    pendingRequests: requestState.pending.size,
    completedRequests: requestState.completed.size,
    cacheSize: requestCache.size,
  };
};

// 设置全局默认配置
export const setGlobalDefaults = (defaults: Partial<AxiosRequestConfig>) => {
  Object.assign(httpClient.defaults, defaults);
};

// 导出http客户端实例（用于特殊需求）
export { httpClient };

// 保持向后兼容的默认导出
export default httpClient;

// AI请求专用函数，使用Python后端
export const aiHttpPost = async <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  const aiClient = axios.create({
    baseURL: ENV_CONFIG.AI_API_BASE_URL, // 使用AI服务地址
    timeout: 60000, // AI请求可能需要更长时间
    withCredentials: false,
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      Accept: "application/json",
      "Cache-Control": "no-cache",
      Pragma: "no-cache",
    },
  });

  try {
    if (ENV_CONFIG.DEBUG) {
      console.log("🤖 AI Request:", {
        url: url,
        method: "POST",
        baseURL: ENV_CONFIG.AI_API_BASE_URL,
        fullURL: `${ENV_CONFIG.AI_API_BASE_URL}${url}`,
        data: data,
      });
    }

    const response = await aiClient.post(url, data, config);
    
    if (ENV_CONFIG.DEBUG) {
      console.log("🤖 AI Response:", {
        url: response.config.url,
        status: response.status,
        data: response.data,
      });
    }

    return response.data;
  } catch (error) {
    console.error("❌ AI Request Error:", error);
    throw error;
  }
};

// AI流式请求函数
export const aiHttpStream = async (
  url: string,
  data?: any,
  onMessage?: (message: string) => void,
  onError?: (error: any) => void,
  onComplete?: () => void
): Promise<void> => {
  try {
    const response = await fetch(`${ENV_CONFIG.AI_API_BASE_URL}${url}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error('No response body');
    }

    const decoder = new TextDecoder();
    
    while (true) {
      const { done, value } = await reader.read();
      
      if (done) {
        onComplete?.();
        break;
      }

      const chunk = decoder.decode(value);
      const lines = chunk.split('\n');
      
      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.slice(6);
          if (data && data !== '[DONE]') {
            try {
              const parsed = JSON.parse(data);
              if (parsed.data) {
                onMessage?.(parsed.data);
              }
            } catch (e) {
              // 忽略解析错误
            }
          }
        }
      }
    }
  } catch (error) {
    console.error("❌ AI Stream Error:", error);
    onError?.(error);
  }
};
